﻿using System.Collections.Generic;
using System.IO;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using ZilLion.Service.Core.ConfigManager.Manager;
using ZilLion.Service.Core.Infrastructure;

namespace ZilLion.Service.Core.Starter.Config
{
    public class SwaggerGenConfig
    {
        private static readonly IList<string> CacheDescList = new List<string>();

        public static void GetDescList()
        {
            var basePath = PlatformServices.Default.Application.ApplicationBasePath;
            foreach (var module in ZilLionConfigurationManager.GetConfigInstance<WebApiAppConfig>().WebModules)
            {
                var path = Path.Combine(basePath, 
                    $"ZilLion.Service.{module}.Controllers.xml");

                if (File.Exists(path))
                    CacheDescList.Add(path);
            }
        }

        public static void ConfigureServices(IServiceCollection services)
        {
            // Swagger - Enable this line and the related lines in Configure method to enable swagger UI
            services.AddSwaggerGen(options =>
            {
                GetDescList();
                options.SwaggerDoc("v1", new Info {Title = "纵联科技API", Version = "v1"});
                options.DocInclusionPredicate((docName, description) => true);
                IncludeXmlComments(options);
            });
        }

        public static void IncludeXmlComments(SwaggerGenOptions config)
        {
            foreach (var descpath in CacheDescList)

                config.IncludeXmlComments(descpath);
        }
    }
}